package com.cqeec.gams.service;

import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cqeec.gams.dao.RoleMapper;
import com.cqeec.gams.dao.RolePermissionsMapper;
import com.cqeec.gams.entity.Role;
import com.cqeec.gams.entity.RolePermissions;

/**
 * 角色服务类。
 * 
 * @author 唐杰
 *
 */
@Service
public class RoleServiceImpl implements RoleService {
	@Autowired
	private RoleMapper roleMapper;

	@Autowired
	private RolePermissionsMapper rpMapper;

	@Override
	public long count() {
		return roleMapper.count();
	}

	@Override
	public List<Role> findAll() {
		return roleMapper.findAll();
	}

	@Override
	public Role findById(String id) {
		return roleMapper.findById(id);
	}

	@Override
	public List<Role> findPage(int pageNumber, int pageSize) {
		return roleMapper.findPage(pageNumber, pageSize);
	}

	@Override
	public void insert(Role entity) {
		roleMapper.insert(entity);
	}

	@Override
	public void update(Role entity) {
		roleMapper.update(entity);
	}

	@Override
	public void delete(String id) {
		roleMapper.delete(id);
	}

	@Override
	public List<Role> findByConditionPage(int pageNumber, int pageSize, Role role) {
		return roleMapper.findByConditionPage(pageNumber, pageSize, role);
	}

	@Override
	public long count(Role role) {
		return roleMapper.countByCondition(role);
	}

	@Override
	public void insert(Role role, String[] functions) {
		roleMapper.insert(role);
		if (functions != null) {
			// 插入角色权限信息
			RolePermissions rp;
			for (String funId : functions) {
				rp = new RolePermissions();
				rp.setId(UUID.randomUUID().toString());
				rp.setRole(role.getId());
				rp.setFunctionalModule(funId);
				rpMapper.insert(rp);
			}
		}
	}

	@Override
	public void update(Role role, String[] functions) {
		roleMapper.update(role);
		// 删除原有角色权限信息
		rpMapper.deleteRolePermissions(role.getId());
		if (functions != null) {
			// 插入角色权限信息
			RolePermissions rp;
			for (String funId : functions) {
				rp = new RolePermissions();
				rp.setId(UUID.randomUUID().toString());
				rp.setRole(role.getId());
				rp.setFunctionalModule(funId);
				rpMapper.insert(rp);
			}
		}
	}

}
